﻿using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using DataAccessLayer.EntityDataModel;
using Dev_house_Project.DataAccessLayer.EntityDataModel;

namespace Dev_house_Project.Providers.DataProviders
{
    /// <summary>
    /// Data provider for companies.
    /// </summary>
    public class CompanyDataProvider
    {
        #region Fields

        private readonly EntityDataModel _context;

        #endregion

        #region Constructors
        /// <summary>
        /// Default constructor.
        /// </summary>
        /// <param name="connectionString">Data base connection string.</param>
        public CompanyDataProvider(string connectionString)
        {
            connectionString = ConfigurationManager.ConnectionStrings["RemoteEntityDataModel"].ConnectionString;
            _context = new EntityDataModel(connectionString);
        }
        
        #endregion

        #region Methods

        /// <summary>
        /// Get all companies from data base.
        /// </summary>
        /// <returns>List of companies.</returns>
        public List<Company> GetAllCompanies()
        {
            IQueryable<Company> list = from company in _context.CompanySet
                                       select company;
            return list.ToList();
        }

        /// <summary>
        /// Save copmanies to data base.
        /// </summary>
        /// <param name="companies">List of companies.</param>
        public void SaveCompanies(List<Company> companies)
        {
            foreach (Company company in companies)
            {
                _context.Attach(company);
                company.SetAllModified(_context); // custom extension method

                try
                {
                    _context.SaveChanges();
                }
                catch (OptimisticConcurrencyException e)
                {
                    throw (e);
                }
            }
        }
        
        #endregion
    }
}